//
//  VipInfo3ViewController.m
//  fitnessmanage
//
//  Created by 众拳科技 on 2017/10/27.
//  Copyright © 2017年 zongquankeji. All rights reserved.
//

#import "VipInfo3ViewController.h"
#import "VipInfoRecordTableViewCell.h"
#import "ZLPhotoPickerViewController.h"
#import "UIImage+ZLPhotoLib.h"
#import "ZLPhotoPickerBrowserPhoto.h"

@interface VipInfo3ViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    
    int startIndex;
    
    int pageSize;
}

@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,weak)UIButton *imageBtn;

@property(nonatomic,weak)UIButton *camBtn;

@property(nonatomic,weak)UIButton *addBtn;

@property(nonatomic,weak)UIView *whiteView;

@property(nonatomic,weak)UITextField *inputTF;

@property(nonatomic,weak)UIButton *sureBtn;

@property(nonatomic,strong)NoDataView *noDataView;

@property(nonatomic,strong)NSMutableArray *dataSource;

@property (nonatomic , strong) ZLPhotoPickerBrowserPhoto *photo;

@end

@implementation VipInfo3ViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];

    self.view.backgroundColor = BackGroundColor;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UIView *whiteView = [[UIView alloc] init];
    whiteView.backgroundColor = CSColorFromRGB(0xf5f5f6);
    whiteView.layer.borderWidth = 1.0;
    whiteView.layer.borderColor = CSColorFromRGB(0xd7d7d9).CGColor;
    [self.view addSubview:whiteView];
    self.whiteView = whiteView;
    [whiteView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(-CZQ_SaferTabbarHeight);
        make.height.mas_equalTo(60);
    }];
    
    UIButton *sureBtn = [[UIButton alloc] init];
    sureBtn.backgroundColor = ButtonBackGroundColor;
    sureBtn.layer.cornerRadius = 2;
    sureBtn.layer.masksToBounds = YES;
    sureBtn.titleLabel.font = MidBigFont;
    [sureBtn setTitleColor:CSColorFromRGB(0x0a0a0a)];
    [sureBtn setTitle:@"确定"];
    [sureBtn addTarget:self action:@selector(sendMemo)];
    sureBtn.hidden = YES;
    [whiteView addSubview:sureBtn];
    self.sureBtn = sureBtn;
    
    UIButton *addBtn = [[UIButton alloc] init];
    [addBtn setImage:@"icon_sendadd"];
    [addBtn addTarget:self action:@selector(addBtnClick:)];
    [whiteView addSubview:addBtn];
    self.addBtn = addBtn;
    
    UITextField *inputTF = [[UITextField alloc] init];
    inputTF.font = MidFont;
    inputTF.placeholder = @"请输入";
    inputTF.delegate = self;
    //inputTF.backgroundColor = CSRedColor;
    [whiteView addSubview:inputTF];
    self.inputTF = inputTF;
    [inputTF mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(whiteView).offset(10);
        make.left.mas_equalTo(whiteView).offset(10);
        make.height.mas_equalTo(50);
        make.right.mas_equalTo(self.addBtn.mas_left).offset(-10);
    }];

    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = LineBackGroundColor;
    [whiteView addSubview:lineView];
    [lineView mas_remakeConstraints:^(MASConstraintMaker *make) {       
        make.top.mas_equalTo(inputTF.mas_bottom);
        make.left.width.mas_equalTo(whiteView);
        make.height.mas_equalTo(1);
    }];
    
    [addBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(whiteView).offset(-10);
        make.centerY.mas_equalTo(inputTF);
        make.width.height.mas_equalTo(30);
    }];
    
    [sureBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
    
        make.right.mas_equalTo(whiteView).offset(-10);
        make.centerY.mas_equalTo(inputTF);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(60);
    }];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.estimatedRowHeight = 200;
    [tableView registerClass:[VipInfoRecordTableViewCell class] forCellReuseIdentifier:@"VipInfoRecordTableViewCell"];
    [tableView registerClass:[VipInfoRecordTableViewCell class] forCellReuseIdentifier:@"VipInfoRecordTableViewCellImage"];
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    tableView.backgroundColor = CSClearColor;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.width.mas_equalTo(self.view);
        make.bottom.mas_equalTo(whiteView.mas_top);
    }];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyHidden = YES;
    
    
    MyTableHead *mj_head = [MyTableHead headerWithRefreshingTarget:self refreshingAction:@selector(loadStartData)];
    tableView.mj_header = mj_head;
    tableView.mj_footer = footer;
    [tableView.mj_header beginRefreshing];
}

#pragma mark 下拉
-(void)loadStartData{
    
    startIndex = 1;
    
    pageSize = 20;
    
    [self loadData];
}

#pragma mark 上拉
-(void)loadMoreData{
    
    startIndex = startIndex + 1;
    
    [self loadData];
}

-(void)loadData{
    
    //GET_MemberRecordListDat
 
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    
    
    [params setObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"ShopID"] forKey:@"ShopID"];
    
    [params setObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"UserID"] forKey:@"MemberID"];
    
    [params setObject:[NSString stringWithFormat:@"%d",startIndex] forKey:@"page"];
    
    [params setObject:[NSString stringWithFormat:@"%d",pageSize] forKey:@"rows"];
    
    [HTTPTool GET:GET_MemberRecordListDat parameters:params

          success:^(id responseObject){

              [MBProgressHUD hideHUDForView:self.view];

              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {

                  NSMutableArray *resultArray = [responseObject objectForKey:@"rows"];

                  if (resultArray.count > 0) {

                      [self.tableView.mj_header endRefreshing];

                      [self.tableView.mj_footer endRefreshing];
                  }
                  else{

                      [self.tableView.mj_header endRefreshing];

                      [self.tableView.mj_footer endRefreshingWithNoMoreData];
                  }

                  self.noDataView = [NoDataView shareInstance];

                  [self.noDataView hideInView:self.view];

                  if (startIndex == 1) {

                      self.dataSource = [NSMutableArray arrayWithArray:resultArray];

                      if (self.dataSource.count == 0) {

                          self.noDataView = [NoDataView shareInstance];

                          [self.noDataView showInView:self.view];
                      }
                  }
                  else{

                      [self.dataSource addObjectsFromArray:resultArray];
                  }

                  [self.view bringSubviewToFront:self.tableView];
                  [self.view bringSubviewToFront:self.whiteView];

                  [self.tableView reloadData];
              }

          }

          failure:^(NSError *error){

              [self.tableView.mj_header endRefreshing];

              self.noDataView = [NoDataView shareInstance];

              [self.noDataView showInView:self.view];

              [MBProgressHUD hideHUDForView:self.view];
          }];
    [self.tableView.mj_header endRefreshing];
}


#pragma mark UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSource.count;
}

#pragma mark UITableViewDelegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NSDictionary *dict = [self.dataSource objectAtIndex:indexPath.row];
    
    NSString *memo = [dict objectForKey:@"Memo"];
    
    VipInfoRecordTableViewCell *cell;
    
    if ([memo rangeOfString:QiNiuBase].location == NSNotFound) {
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"VipInfoRecordTableViewCell"];
        
    } else {
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"VipInfoRecordTableViewCellImage"];
    }
    
    
    cell.detailText = memo;
    
    NSString *time = [dict objectForKey:@"AddTime"];
    
    cell.timeLabel.text = time;
    
    [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:[[dict objectForKey:@"Pic"] isNull]?nil:[dict objectForKey:@"Pic"]] placeholderImage:PlaceHold];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}


#pragma mark 更多按钮点击
-(void)addBtnClick:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    
    if (btn.selected) {
    
        [self.whiteView mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.left.width.mas_equalTo(self.view);
            make.bottom.mas_equalTo(-CZQ_SaferTabbarHeight);
            make.height.mas_equalTo(50 + 90);
        }];
        
        UIButton *imageBtn = [[UIButton alloc] init];
        [imageBtn addTarget:self action:@selector(vipHeadSelect)];
        [imageBtn setImage:@"icon_images"];
        [self.whiteView addSubview:imageBtn];
        self.imageBtn = imageBtn;
        
        [imageBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
           
            make.top.mas_equalTo(self.inputTF.mas_bottom).offset(10);
            
            make.left.mas_equalTo(self.whiteView).offset(20);
            
            make.height.width.mas_equalTo(60);
        }];
        
        UIButton *camerBtn = [[UIButton alloc] init];
        [camerBtn setImage:@"icon_shot"];
        [camerBtn addTarget:self action:@selector(vipHeadSelect)];
        [self.whiteView addSubview:camerBtn];
        self.camBtn = camerBtn;
        [camerBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.left.mas_equalTo(imageBtn.mas_right).offset(15);
            
            make.top.width.height.mas_equalTo(imageBtn);
        }];
        
    }
    else{
        
        [self.camBtn removeFromSuperview];
        
        [self.imageBtn removeFromSuperview];
        
        self.camBtn = nil;
        
        self.imageBtn = nil;
        
        [self.whiteView mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.left.width.mas_equalTo(self.view);
            make.bottom.mas_equalTo(self.view);
            make.height.mas_equalTo(60);
        }];
    }
    
}

#pragma mark 选择头像
-(void)vipHeadSelect{
    
    ZLPhotoPickerViewController *pickerVc = [[ZLPhotoPickerViewController alloc] init];
    
    pickerVc.maxCount = 1;
    
    // Jump AssetsVc
    pickerVc.status = PickerViewShowStatusCameraRoll;
    // Recoder Select Assets
    //    pickerVc.selectPickers = self.assets;
    // Filter: PickerPhotoStatusAllVideoAndPhotos, PickerPhotoStatusVideos, PickerPhotoStatusPhotos.
    
    pickerVc.isShowCamera = YES;
    pickerVc.photoStatus = PickerPhotoStatusPhotos;
    // Desc Show Photos, And Suppor Camera
    pickerVc.topShowPhotoPicker = YES;
    
    // CallBack
    __weak typeof(self)weakSelf = self;
    
    pickerVc.callBack = ^(NSArray<ZLPhotoAssets *> *status){
        
        for (ZLPhotoAssets *assets in status) {
            
            ZLPhotoPickerBrowserPhoto *photo = [ZLPhotoPickerBrowserPhoto photoAnyImageObjWith:assets];
            
            photo.asset = assets;
            
            weakSelf.photo = photo;
            
            [weakSelf uploadImage];
            
            break;
        }
    };
    
    [pickerVc showPickerVc:self];
}

#pragma mark 上传头像
-(void)uploadImage{
    
    if (!self.photo) {
        
        return;
    }
    
    NSData *imageData;
    
    UIImage *image;
    
    if ([self.photo.asset isKindOfClass:[UIImage class]]) {
        
        image = (UIImage *)self.photo.asset;
    }
    else{
        
        image = [self.photo.asset originImage];
    }
    
    imageData  = UIImageJPEGRepresentation(image,0.1);
    
    [MBProgressHUD showMessage:@"上传中.." toView:self.view];
    
    RAYUploader *upload = [RAYUploader defaultUploader];
    
    [upload uploadWithData:imageData complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        if (key) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSString *picUrl = [NSString stringWithFormat:@"%@%@",QiNiuBase,key];
                
                [self addRecordWithMemo:picUrl];
            });
            
        }
        
    }];
    
}


#pragma mark 发送记录
-(void)sendMemo{
    
    NSString *memo = self.inputTF.text;
    
    if ([memo isEmptyString]) {
        
        [MBProgressHUD showText:@"请输入内容"];
        
        return;
    }
    
    self.inputTF.text = @"";
    
    [self addRecordWithMemo:memo];
    
    [self.view endEditing:YES];
}

#pragma mark 添加跟踪记录
-(void)addRecordWithMemo:(NSString *)memo{
    
    [MBProgressHUD showMessage:@"请求中..." toView:self.view];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
//    VenueModel *venue = [VenueModel venue];
    
    [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ShopID"] forKey:@"ShopID"];
    
    [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"UserID"] forKey:@"MemberID"];
    
    [params setObject:memo forKey:@"Memo"];
    
    [HTTPTool POSTRaw:Post_MemberRecordOperate parameters:params
     
              success:^(id responseObject){
                  
                  [MBProgressHUD hideHUDForView:self.view];
                  
                  if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                      
                      [MBProgressHUD showText:@"添加成功"];
                      
                      [self loadStartData];
                  }
              }
     
              failure:^(NSError *error){
                  
                  [MBProgressHUD hideHUDForView:self.view];
              }];
}

#pragma mark UITextFieldDelegate

// 获得焦点
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    self.sureBtn.hidden = NO;
    
    self.addBtn.hidden = YES;
    
    return YES;
}

// 失去焦点
- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    self.sureBtn.hidden = YES;
    
    self.addBtn.hidden = NO;
}
-(NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        
        _dataSource = [[NSMutableArray alloc] init];
        
    }
    
    return _dataSource;
}

@end
